<template>
  <div>
    <div class="nav">
      <div class="left">
        <a @click="check(0)" :class="0==cate?'active':''">所有宝贝</a>
        <a v-for="i in cates" :key="i.id" @click="check(i.id)" :class="cate==i.id?'active':''">{{i.name}}</a>
      </div>
      <div class="right">
        <input type="text" v-model="keyword">
        <button @click="search">搜索</button>
      </div>
    </div>
    <div class="main">
      <div class="box" v-for="i in goods" :key="i.id">
        <div class="img">
          <img :src="baseUrl+i.img" alt="">
        </div>
        <div>
          <p class="title">{{i.title}}</p>
          <p class="price">￥：{{i.price}}</p>
        </div>
      </div>
    </div>
    <div class="footer">
      <button v-if="previous" @click="pagx(p-1)">&lt;</button>
      <button v-for="i in page" :key="i" @click="pagx(i)" :class="i==p?'active':''">{{i}}</button>
      <button v-if="next" @click="pagx(p+1)">&gt;</button>
      <input type="number" min="1" v-model="p"/>
      <button @click="pagx(p)">跳转</button>
    </div>
  </div>
</template>

<script>
export default {
  data(){
    return{
      keyword:'',
      cates:[],
      goods:[],
      baseUrl:'http://127.0.0.1:8000/static/',
      page:[],
      p:1,
      cate:0,
      previous:false,
      next:false
    }
  },
  mounted(){
    this.get_cate();
    this.get_goods();
  },
  methods:{
    get_cate(){
      this.axios({
        url:'http://127.0.0.1:8000/cate/',
        methods:'get'
      }).then(res=>{
        this.cates=res.data;
      })
    },
    get_goods(){
      this.axios({
        url:'http://127.0.0.1:8000/good/',
        methods:'get',
        params:{'p':this.p,'keyword':this.keyword,'cate':this.cate}
      }).then(res=>{
        this.goods=res.data.data;
        this.page=res.data.page;
        this.previous=res.data.previous;
        this.next=res.data.next;
      })
    },
    pagx:function(p){
      this.p=p;
      this.get_goods();
    },
    search:function(){
      this.p=1;
      this.get_goods();
    },
    check:function(cate){
      this.cate=cate;
      this.get_goods();
    }
  }
}
</script>

<style scoped>
.active{
  background: cornflowerblue;
  color: #ffffff;
}
.nav{
  width: 100%;
  height: 50px;
}
.nav div{
  float: left;
}
.nav .left{
  width: 50%;
  height: 50px;
  line-height: 50px;
}
.nav .left a{
  line-height: 50px;
  margin: 0 10px;
}
.nav .right{
  width: 50%;
  height: 50px;
  line-height: 50px;
  text-align: right;
}
.nav .right input{
  height: 20px;
  width: 200px;
}
.nav .right button{
  height: 26px;
  border: 0;
  margin-right: 16%;
}
.main{
  width: 100%;
  height: 300px;
  margin: 2px 0;
}
.main .box{
  width: 21%;
  height: 300px;
  float: left;
  margin: 0 2%;
}
.main .box .img{
  text-align: center;
}
.main .box .title{
  padding-left: 5%;
}
.main .box .price{
  padding-left: 5%;
}
.footer{
  width: 100%;
  height: 50px;
  text-align: center;
  line-height: 50px;
}
.footer input{
  width: 3%;
}

</style>
